package com.star.mall.file.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.star.mall.base.exception.BusinessException;
import com.star.mall.file.FileService;
import com.star.mall.file.model.IFile;
import com.star.mall.utils.ContextUtil;
import com.star.mall.utils.UniqueIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 本地文件服务
 * @author StarQ
 * @since 2021-05-04
 */

@Service("local")
@Slf4j
@ConditionalOnProperty(
        prefix = "system.file",
        name = {"mode"},
        havingValue = "local",
        matchIfMissing = true
)
public class LocalFileService implements FileService {

    @Value("${system.file.path}")
    private String path;

    @Override
    public void uploadFile(IFile file, InputStream inputStream) {
        try {
            String filePath = getFilePath();
            file.setPath(filePath);
            String key = UniqueIdUtil.getSid();
            file.setKey(key);
            saveFile(inputStream, filePath, getFileName(key, file.getExt()));
        }catch (Exception e) {
            log.error(e.getMessage());
            throw new BusinessException("上传失败");
        }
    }

    private String getFileName(String fileName, String ext) {
        return fileName + "." + ext;
    }

    @Override
    public void saveFile(InputStream inputStream, String filePath, String key) {
        if(!FileUtil.exist(filePath)){
            FileUtil.mkdir(filePath);
        }
        FileUtil.writeFromStream(inputStream, filePath + File.separator + key);
    }

    @Override
    public void downloadFile(String resourceLocation, String fileName, OutputStream outputStream) {
        File file = FileUtil.file(resourceLocation + File.separator + fileName);
        if (!FileUtil.exist(file)) {
            throw new BusinessException("文件不存在");
        }
        byte[] bytes = FileUtil.readBytes(file);
        IoUtil.write(outputStream, true, bytes);
    }

    @Override
    public boolean deleteFile(String resourceLocation, String fileName) {
        File file = FileUtil.file(resourceLocation + File.separator + fileName);
        if (FileUtil.exist(file)) {
            return FileUtil.del(file);
        }
        return false;
    }

    private String getFilePath() {
        return path + File.separator +
                ContextUtil.getCurrentUser().getUsername() +
                File.separator +
                DateUtil.today();
    }

}
